<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" showFooter :width="width" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref, useAttrs } from "vue"
  import { BasicForm, useForm } from "/@/components/Form/index"
  import { formSchema } from "./spec.data"
  import { BasicDrawer, useDrawerInner } from "/@/components/Drawer"
  import { saveOrUpdateSpec } from "./spec.api"
  import { useAdapt } from "/@/hooks/system/useAutoAdapt.ts"
  import { useMessage } from "/@/hooks/web/useMessage"
  const { createMessage } = useMessage()
  // 声明Emits
  const emit = defineEmits(["success", "register"])

  const { width } = useAdapt({ xl: 650, lg: 650, md: 650, sm: 650, xs: 650 })
  const attrs = useAttrs()
  const isUpdate = ref(true)
  const [registerForm, { setProps, resetFields, setFieldsValue, updateSchema, validate }] = useForm({
    labelCol: {
      md: { span: 4 },
      sm: { span: 6 },
    },
    wrapperCol: {
      md: { span: 20 },
      sm: { span: 18 },
    },

    schemas: formSchema,
    showActionButtonGroup: false,
  })

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    await resetFields()
    setDrawerProps({ confirmLoading: false })
    isUpdate.value = !!data?.isUpdate
    console.log("use data: ", data)
    // 转成select结构
    const valueData = data?.record?.valueData?.split(",").map((e) => {
      return { label: e, value: e }
    })
    // 无论新增还是编辑，都可以设置表单值
    if (typeof data.record === "object") {
      let values = {
        ...data.record,
        valueData,
      }
      setFieldsValue(values)
    }
  })
  //获取弹窗标题
  const getTitle = computed(() => (!unref(isUpdate) ? "新增规格" : "编辑规格"))
  //提交事件
  async function handleSubmit() {
    try {
      const values = await validate()
      console.log("submit data: ", values)
      if (values.valueData.includes("[object Object]")) {
        values.valueData = null
      }

      setDrawerProps({ confirmLoading: true })
      await saveOrUpdateSpec({ ...values }, unref(isUpdate))
      closeDrawer()
      createMessage.success(`${getTitle.value}成功`)
      emit("success")
    } finally {
      setDrawerProps({ confirmLoading: false })
    }
  }
</script>
